import { _decorator, Component, Node, Sprite, Color, SpriteFrame, UIOpacity, tween, Vec3, Button, UITransform, Event, AudioClip, AudioSource } from 'cc';
import { TileType } from '../core/BoardManager';
import { UIManager } from '../core/UIManager';

const { ccclass, property } = _decorator;

/**
 * 方块预制体组件
 * 负责单个方块的显示和动画
 */
@ccclass('TilePrefab')
export class TilePrefab extends Component {
    @property(Sprite)
    public sprite: Sprite = null;
    
    @property({type: [SpriteFrame], tooltip: "方块图片数组"})
    public tileSprites: SpriteFrame[] = [];
    
    @property(Button)
    private button: Button = null;
    
    @property({type: AudioClip, tooltip: "点击音效"})
    public clickSound: AudioClip = null;
    
    private _tileType: TileType = TileType.NONE;
    private _row: number = -1;
    private _col: number = -1;
    private _isSelected: boolean = false;
    private _isMatched: boolean = false;
    
    // 动画参数
    private readonly selectScale: number = 1.1;
    private readonly matchFadeTime: number = 0.3;
    private readonly moveTime: number = 0.2;
    private readonly newTileTime: number = 0.3;
    
    private _audioSource: AudioSource = null;
    
    /**
     * 初始化方块
     */
    public init(type: TileType, row: number, col: number): void {
        this._tileType = type;
        this._row = row;
        this._col = col;
        this._isSelected = false;
        this._isMatched = false;
        
        this.updateSprite();
        
        // 重置变换
        this.node.scale = new Vec3(1, 1, 1);
        const opacity = this.getComponent(UIOpacity);
        if (opacity) {
            opacity.opacity = 255;
        }

        // 确保有Button组件
        if (!this.button) {
            this.button = this.getComponent(Button);
        }

        // 确保有AudioSource组件
        this._audioSource = this.getComponent(AudioSource);
        if (!this._audioSource) {
            this._audioSource = this.addComponent(AudioSource);
        }

        // 先移除旧的事件监听器，防止重复绑定
        if (this.button) {
            this.button.node.off(Button.EventType.CLICK, this.onTileClicked, this);
            // 添加点击事件监听
            this.button.node.on(Button.EventType.CLICK, this.onTileClicked, this);
            console.log(`添加点击事件监听: row=${this._row}, col=${this._col}`);
        } else {
            console.error("Button组件为空，无法添加点击事件监听!");
        }
    }
    
    /**
     * 更新方块图片
     */
    private updateSprite(): void {
        if (!this.sprite) return;
        
        // 尝试从数组获取精灵帧
        if (this.tileSprites.length > this._tileType && this.tileSprites[this._tileType]) {
            this.sprite.spriteFrame = this.tileSprites[this._tileType];
            return;
        }
        
        // 如果没有精灵帧，尝试从UI管理器加载
        const tileNames = ["tile_red", "tile_blue", "tile_green", "tile_yellow", "tile_purple"];
        if (this._tileType >= 0 && this._tileType < tileNames.length) {
            const tileName = tileNames[this._tileType];
            
            if (UIManager.instance) {
                UIManager.instance.loadUI(`ui/${tileName}`).then(spriteFrame => {
                    if (this.sprite && this.isValid) {
                        this.sprite.spriteFrame = spriteFrame;
                    }
                }).catch(err => {
                    console.error(`加载方块图片失败: ${tileName}`, err);
                });
            }
        }
    }
    
    /**
     * 选中方块
     */
    public select(): void {
        if (this._isSelected) return;
        
        this._isSelected = true;
        
        // 播放选中动画
        tween(this.node)
            .to(0.1, { scale: new Vec3(this.selectScale, this.selectScale, 1) }, {
                easing: 'backOut'
            })
            .start();
    }
    
    /**
     * 取消选中方块
     */
    public deselect(): void {
        if (!this._isSelected) return;
        
        this._isSelected = false;
        
        // 播放取消选中动画
        tween(this.node)
            .to(0.1, { scale: new Vec3(1, 1, 1) }, {
                easing: 'backIn'
            })
            .start();
    }
    
    /**
     * 标记方块为已匹配
     */
    public markAsMatched(): void {
        this._isMatched = true;
    }
    
    /**
     * 检查方块是否已匹配
     */
    public isMatched(): boolean {
        return this._isMatched;
    }
    
    /**
     * 播放消除动画
     */
    public playMatchAnimation(callback?: Function): void {
        const opacity = this.getComponent(UIOpacity) || this.addComponent(UIOpacity);
        
        // 播放消除动画
        tween(opacity)
            .to(this.matchFadeTime, { opacity: 0 })
            .call(() => {
                if (callback) callback();
            })
            .start();
    }
    
    /**
     * 播放移动动画
     */
    public playMoveAnimation(targetPos: Vec3, callback?: Function): void {
        tween(this.node)
            .to(this.moveTime, { position: targetPos }, {
                easing: 'quadOut'
            })
            .call(() => {
                if (callback) callback();
            })
            .start();
    }
    
    /**
     * 播放新方块动画
     */
    public playNewTileAnimation(callback?: Function): void {
        // 设置初始状态
        this.node.scale = new Vec3(0, 0, 1);
        
        // 播放出现动画
        tween(this.node)
            .to(this.newTileTime, { scale: new Vec3(1, 1, 1) }, {
                easing: 'backOut'
            })
            .call(() => {
                if (callback) callback();
            })
            .start();
    }
    
    /**
     * 获取方块类型
     */
    public get tileType(): TileType {
        return this._tileType;
    }
    
    /**
     * 设置方块类型
     */
    public set tileType(type: TileType) {
        this._tileType = type;
        this.updateSprite();
    }
    
    /**
     * 获取方块行
     */
    public get row(): number {
        return this._row;
    }
    
    /**
     * 设置方块行
     */
    public set row(row: number) {
        this._row = row;
    }
    
    /**
     * 获取方块列
     */
    public get col(): number {
        return this._col;
    }
    
    /**
     * 设置方块列
     */
    public set col(col: number) {
        this._col = col;
    }

    onLoad() {
        // 确保有Button组件
        if (!this.button) {
            this.button = this.getComponent(Button);
        }

        // 确保有AudioSource组件
        this._audioSource = this.getComponent(AudioSource);
        if (!this._audioSource) {
            this._audioSource = this.addComponent(AudioSource);
        }

        // 添加点击事件监听
        this.button.node.on(Button.EventType.CLICK, this.onTileClicked, this);
    }

    onDestroy() {
        // 清理事件监听
        this.button.node.off(Button.EventType.CLICK, this.onTileClicked, this);
    }

    private onTileClicked() {
        console.log(`Tile clicked: row=${this._row}, col=${this._col}`);
        
        // 注意：不需要在这里播放音效，因为已经通过全局按钮点击事件处理了
        
        // 发送自定义事件
        const event = new Event('tileClicked');
        event['detail'] = { row: this._row, col: this._col };
        this.node.dispatchEvent(event);
    }
} 